let aes = require('./aes.js');
// #ifdef H5
import wx from 'jweixin-module';
// #endif
let status = 1;
let factory_id=2;   // 2 
// let factory_id=5;   //
let appid='wx84987f37fef0dc1f';
let version='1.0.5';
let notice = 0;
let KEY = 'rMxrRACC30d85pMa';
let IV = 'xcVxZJMTdhXD9ZEb';


// let http_url = 'https://api.cxbyi.com';
// let h5_img_url = 'https://h5.cxbyi.com';
// let h5_share_url="https://h5.cxbyi.com/pages/redirect-h5/redirect-h5"
// let config_url = 'https://api.cxbyi.com';

// let http_url = 'https://api.ldsp.cxbyi.com/v'+version;
// let h5_img_url = 'https://h5.riyuexin.cxbyi.com';
// let h5_share_url="https://h5.riyuexin.cxbyi.com/pages/redirect-h5/redirect-h5"
// let config_url = 'https://api.ldsp.cxbyi.com';


let http_url = 'https://api.ldsp.cxbyi.com/v'+version;
let h5_img_url = 'https://h5.ldsp.cxbyi.com';
let h5_share_url="https://h5.ldsp.cxbyi.com/pages/redirect-h5/redirect-h5"
let config_url = 'https://api.ldsp.cxbyi.com';






let img_upload = http_url+'/upload/image';
let video_upload = http_url+'/upload/video';


// let h5_share_name = '日月鑫';
let h5_share_name = '领得';





let share_url = 'http://o.ldsp.cxbyi.com/mp';
// let share_url = 'http://o.riyuexin.cxbyi.com/mp';
// let share_url = 'http://o.cxbyi.com/xingtian_mp';
let share_title = '';
let errMsg = {
	'40001':'厂家信息无效(factory-id错误)',
	'40003':'用户token无效(例:错误、过期，需要重新登录)',
	'40004':'请求失败',
	'40005':'参数错误',
	'40006':'请求参数包含敏感词',
	'40007':'商品库存不足'
}




// #ifdef H5
	const request = function(options) {
	    options = options || {};
	    options.url=http_url+options.url;
	    options.data = options.data || {};
	    options.time = options.time || 60000 ;
	
	    var callbackName = ('jsonp_' + Math.random()).replace(".", "");
	    var oHead = document.getElementsByTagName('head')[0];
	    // var params = formatData(options.data, false);
		options.data.header_factory_id = factory_id;
		options.data.header_token = uni.getStorageSync('token') || "";
		options.data.header_version = version;
		// console.log(options.data)
		let params = encrypt(JSON.stringify(options.data));
	    var oS = document.createElement('script');
	    oHead.appendChild(oS);
	
	    //create jsonp callback
	    window[callbackName] = function (res) {
			// console.log(res)
	    	clearTimeout(oS.timer);
	        oHead.removeChild(oS);
	        window[callbackName] = null;
	        var err_code = res.code;
				let result_data =null;
				if(res.result!==null){
					result_data = decrypt(res.result);
				}
				res.result = result_data ? JSON.parse(result_data) : null;
				switch(err_code) {
				   case 200:
				   case 40006:
				   case 40003:
				      return typeof options.success === 'function' && options.success(res);
				      break;
				   case 40001:
				   uni.showToast({
				   	title:'系统异常~',
				   	icon:"none",
				   	duration:2000
				   })
				   break;
				   case 40004:
				   uni.showToast({
				   	title:'请求失败~请重试',
				   	icon:"none",
				   	duration:2000
				   })
				   break;
				   case 40005:
				   uni.showToast({
				   	title:res.msg,
				   	icon:"none",
				   	duration:2000
				   })
				   break;
				   case 40007:
				     uni.showToast({
				     	title:'库存不足~',
				     	icon:"none",
				     	duration:2000
				     })
				     break;	
				   default:
				      uni.showToast({
				      	title:res.msg,
				      	icon:"none",
				      	duration:2000
				      });
					  return typeof options.success === 'function' && options.success(res);
				} 
	    };
		var src = '';
		if(options.url.indexOf("?") != -1){
			src = options.url + '&__callback=' + callbackName;
		}else{
			src = options.url + '?__callback=' + callbackName;
		}
	      
	    // if(options.data) {
	    // 	var maps = options.data;
	    // 	for(var attr in maps) {
	    // 		src += ('&' + attr + '=' + maps[attr]);
	    // 	}
	    // }
	    src += ('&params=' + params);
	    oS.src = src;
	    oS.timer = setTimeout(function () {
	        window[callbackName] = null;
	        oHead.removeChild(oS);
	        options.error && options.error({ message: "超时" });
	    }, options.time);
	};
	
	const request_config = function(options) {
	    options = options || {};
	    options.url=http_url+options.url;
	    options.data = options.data || {};
	    options.time = options.time || 60000 ;
	
	    var callbackName = ('jsonp_' + Math.random()).replace(".", "");
	    var oHead = document.getElementsByTagName('head')[0];
	    // var params = formatData(options.data, false);
		options.data.header_factory_id = factory_id;
		options.data.header_token = uni.getStorageSync('token') || "";
		options.data.header_version = version;
		// console.log(options.data)
		let params = encrypt(JSON.stringify(options.data));
	    var oS = document.createElement('script');
	    oHead.appendChild(oS);
	
	    //create jsonp callback
	    window[callbackName] = function (res) {
	    	clearTimeout(oS.timer);
	        oHead.removeChild(oS);
	        window[callbackName] = null;
			return typeof options.success === 'function' && options.success(res);
	    };
		var src = '';
		if(options.url.indexOf("?") != -1){
			src = options.url + '&__callback=' + callbackName;
		}else{
			src = options.url + '?__callback=' + callbackName;
		}
	      
	    // if(options.data) {
	    // 	var maps = options.data;
	    // 	for(var attr in maps) {
	    // 		src += ('&' + attr + '=' + maps[attr]);
	    // 	}
	    // }
	    src += ('&params=' + params);
	    oS.src = src;
	    oS.timer = setTimeout(function () {
	        window[callbackName] = null;
	        oHead.removeChild(oS);
	        options.error && options.error({ message: "超时" });
	    }, options.time);
	};
	
	const request_res = function(options) {
	    options = options || {};
	    options.url=http_url+options.url;
	    options.data = options.data || {};
	    
	    options.time = options.time || 60000 ;
	
	    var callbackName = ('jsonp_' + Math.random()).replace(".", "");
	    var oHead = document.getElementsByTagName('head')[0];
	    // var params = formatData(options.data, false);
		options.data.header_factory_id = factory_id;
		options.data.token = uni.getStorageSync('token') || "";
		options.data.version = version;
		let params = encrypt(JSON.stringify(options.data));
	    var oS = document.createElement('script');
	    oHead.appendChild(oS);
	
	    //create jsonp callback
	    window[callbackName] = function (res) {
	    	clearTimeout(oS.timer);
	        oHead.removeChild(oS);
	        window[callbackName] = null;
	        var err_code = res.code;
	        let result_data =null;
	        if(res.result!==null){
	        	result_data = decrypt(res.result);
	        }
	        res.result = result_data ? JSON.parse(result_data) : null;
	        switch(err_code) {
	             case 200:
	             case 40006:
	        	 case 40003:
	                return typeof options.success === 'function' && options.success(res);
	                break;
	        }  
	    };
	
	    var src  = options.url + '?__callback=' + callbackName;
	    if(options.data) {
	    	var maps = options.data;
	    	for(var attr in maps) {
	    		src += ('&' + attr + '=' + maps[attr]);
	    	}
	    }
	    src += ('&params=' + params);
	    oS.src = src;
	    oS.timer = setTimeout(function () {
	        window[callbackName] = null;
	        oHead.removeChild(oS);
	        options.error && options.error({ message: "超时" });
	    }, options.time);
	};
	const wx_config = function(){
		let path='';
		switch (uni.getSystemInfoSync().platform){
			case 'android':
			 path = location.href.split('#')[0];
				break;
			case 'ios':
			 path = uni.getStorageSync('ios_wx_url');
				break;
			default:
			 path = location.href.split('#')[0];
				break;
		}
		request_config({
			url:'/web/wechat/signature',
			data:{
				url:encodeURIComponent(path)
			},
			success:function(res){
				if(res.code==200){
					let result = res.result;
					uni.setStorageSync('wx_js_config',result)
					wx_js_cfg();
				}else{
					
				}
			}
		});
	}
	const wx_js_cfg = function(){
		var res_ult = uni.getStorageSync('wx_js_config');
		wx.config({
		  debug: false,
		  appId: res_ult.appid, // 必填，公众号的唯一标识
		  timestamp: res_ult.timestamp, // 必填，生成签名的时间戳
		  nonceStr: res_ult.nonce, // 必填，生成签名的随机串
		  signature: res_ult.signature, // 必填，签名
		  jsApiList: [
		    'getLocation',
		    'scanQRCode',
		    'openAddress',
		    'chooseImage',
		    'previewImage',
		    'downloadImage',
		    'chooseWXPay',
		    'uploadImage',
		    'onMenuShareTimeline',
		    'openLocation',
		    'onMenuShareAppMessage',
		  ] // 必填，需要使用的JS接口列表
		});
		wx.ready(function () {      //需在用户可能点击分享按钮前就先调用
		
		let share_time_line = uni.getStorageSync('share_time_line');
		let share_app_message = uni.getStorageSync('share_app_message');
		  wx.onMenuShareTimeline({ 
		    title:share_time_line.title || h5_share_name, // 分享标题
		    link: share_time_line.link || h5_share_url+'?page=index', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
		    imgUrl: share_time_line.imgUrl || h5_img_url+'/static/images/logo.png', // 分享图标
		    success: function () {
		    // 用户点击了分享后执行的回调函数
		    }
		  });
		  wx.onMenuShareAppMessage({
		    title:share_app_message.title || h5_share_name, // 分享标题
		    desc:share_app_message.desc || '我发现了一个很不错的商城，买家具有超大实惠！', // 分享描述
		    link: share_app_message.link || h5_share_url+'?page=index', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
		    imgUrl: share_app_message.imgUrl || h5_img_url+'/static/images/logo.png', // 分享图标
		    type:  '', // 分享类型,music、video或link，不填默认为link
		    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
		    success: function () {
		      // 用户点击了分享后执行的回调函数
		    }
		  });
		});
		wx.error(function(res){
			// wx_config()
		  switch(uni.getSystemInfoSync().platform){
		     case 'android':
		        wx_config()
		        break;
		     case 'ios':
		        window.location.reload()
		        break;
		     default:
		 		wx_config()
		 }
		});
	}
// #endif

// #ifdef MP-WEIXIN
	const request = function(option) {
		let that = this
		let params = encrypt(JSON.stringify(option.data));
		uni.request({
			url:http_url+option.url,
			data: option.data ? {params : params} : {},
			header: {
				'factory-id': that.factory_id,
				'token': uni.getStorageSync('token') || "",
				'version':version
			},
			method:"POST",
			success: function(res) {
				var err_code = res.data.code;
				let result_data =null;
				if(res.data.result!==null){
					result_data = decrypt(res.data.result);
				}
				res.data.result = result_data ? JSON.parse(result_data) : null;
				// console.log(res.data)
				switch(err_code) {
				   case 200:
				   case 40006:
				   case 40003:
				      return typeof option.success === 'function' && option.success(res.data);
				      break;
				   case 40001:
				   uni.showToast({
				   	title:'系统异常~',
				   	icon:"none",
				   	duration:2000
				   })
				   break;
				   case 40004:
				   uni.showToast({
				   	title:'请求失败~请重试',
				   	icon:"none",
				   	duration:2000
				   })
				   break;
				   case 40005:
				   uni.showToast({
				   	title:res.data.msg,
				   	icon:"none",
				   	duration:2000
				   })
				   break;
				   case 40007:
				     uni.showToast({
				     	title:'库存不足~',
				     	icon:"none",
				     	duration:2000
				     })
				     break;	
				   default:
				      uni.showToast({
				      	title:res.data.msg,
				      	icon:"none",
				      	duration:2000
				      });
					  return typeof option.success === 'function' && option.success(res.data);
				}  
			},
			complete:function(){
				 typeof option.complete === 'function' && option.complete();
			}
		})
	}
	const request_config = function(option) {
		let that = this
		let params = encrypt(JSON.stringify(option.data));
		uni.request({
			url:config_url+option.url,
			data: option.data ? {params : params} : {},
			header: {
				'factory-id': that.factory_id,
				'version':version
			},
			method:"POST",
			success: function(res) {
				console.log(res.data)
				return typeof option.success === 'function' && option.success(res.data); 
			},
			complete:function(){
				 typeof option.complete === 'function' && option.complete();
			}
		})
	}
	const request_res = function(option) {
		let that = this;
		let params = encrypt(JSON.stringify(option.data));
		uni.request({
			url:http_url+option.url,
			data: option.data ? {params : params} : {},
			data: option.data || {},
			header: {
				'factory-id': that.factory_id,
				'token': uni.getStorageSync('token') || "",
				'version':version
			},
			method:"POST",
			success: function(res) {
				var err_code = res.data.code;
				let result_data =null;
				if(res.data.result!==null){
					result_data = decrypt(res.data.result);
				}
				res.data.result = result_data ? JSON.parse(result_data) : null;
				console.log(res.data)
				switch(err_code) {
				     case 200:
				     case 40006:
					 case 40003:
				        return typeof option.success === 'function' && option.success(res.data);
				        break;
				}  
			},
			complete:function(){
				 typeof option.complete === 'function' && option.complete();
			}
		})
	}
// #endif
// wx小程序



const encrypt = function(str) {
    var key = aes.CryptoJS.enc.Utf8.parse(KEY);
    var iv = aes.CryptoJS.enc.Utf8.parse(IV);
    var encrypted = aes.CryptoJS.AES.encrypt(str,key,{iv:iv,mode:aes.CryptoJS.mode.CBC,padding:aes.CryptoJS.pad.Pkcs7});
    return encrypted.toString();        
}
const decrypt = function(str) {
	var key = aes.CryptoJS.enc.Utf8.parse(KEY);
	var iv = aes.CryptoJS.enc.Utf8.parse(IV);
	var decrypted = aes.CryptoJS.AES.decrypt(str,key,{iv:iv,padding:aes.CryptoJS.pad.Pkcs7});
	return decrypted.toString(aes.CryptoJS.enc.Utf8);
}


export default {
	request,
	factory_id,
	status,
	request_res,
	notice,
	share_url,
	http_url,
	appid,
	img_upload,
	video_upload,
	request_config,
	config_url,
	share_title,
	decrypt,
	encrypt,
	h5_img_url,
	h5_share_name,
	h5_share_url,
	
	// #ifdef H5
	wx_config,
	wx_js_cfg,
	// #endif
	
}